// const Vue = require('vue')
const express = require('express')
const server = express()
const path = require('path')
const LRU = require('lru-cache')
const fs = require('fs')

const proxy = require('http-proxy-middleware')

const { proxyTable, host, port, autoOpenBrowser = false } = require('./config')
// const open = require('open')

const { createBundleRenderer } = require('vue-server-renderer')

const resolve = file => path.resolve(__dirname, file)
const template = fs.readFileSync(path.resolve(__dirname, '../index.template.html'), 'utf-8')

const isProd = process.env.NODE_ENV === 'production'
const serve = (path, cache) => express.static(resolve(path), {
  maxAge: cache && isProd ? 1000 * 60 * 60 * 24 * 30 : 0
})
let isOpened = false

function createRenderer(bundle, options) {
  return createBundleRenderer(bundle, Object.assign(options, {
    template: template,
    cache: LRU({
      max: 1000,
      maxAge: 1000 * 60 * 15
    }),
    basedir: resolve('../dist'),
    runInNewContext: false
  }))
}

let renderer
if (isProd) {
  const bundle = require('../dist/vue-ssr-server-bundle.json')
  const clientManifest = require('../dist/vue-ssr-client-manifest.json')
  renderer = createRenderer(bundle, {
    clientManifest
  })
} else {
  require('../build/setup-dev-server')(server, (bundle, options) => {
    renderer = createRenderer(bundle, options)

    if (autoOpenBrowser && !isOpened) {
      isOpened = true
      require('open')(`http://${host}:${port}`)
    }
  })
}

server.use('/dist', serve('../dist', true))

// 接口代理转发
Object.entries(proxyTable).forEach(([path, opts]) => {
  server.use(path, proxy(opts))
})

// 在服务器处理函数中……
server.get('*', (req, res) => {
  // 这里无需传入一个应用程序，因为在执行 bundle 时已经自动创建过。
  // 现在我们的服务器与应用程序已经解耦！

  const context = {
    url: req.url,
    title: '测试'
  }
  // const app = createApp(context)
  renderer.renderToString(context, (err, html) => {
    if (err) {
      res.status(500).end('Internal Server Error')
      return
    }
    res.end(html)
  })
})

server.listen(port, host, () => {
  console.info(`服务已经启动，服务地址： http://${host}:${port}`)
})
